<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require "vendor/autoload.php";


//账户业务模块
class EmailService extends TP_Service {
    public $redis;
    public function __construct() {
        parent::__construct();
        $this->load->model("SModel/Send_server_model");
        $this->redis = $this->newRedis();
    }



    public function Sendemail($param) {
        if (!isset($param['email'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        if (!filter_var($param['email'], FILTER_VALIDATE_EMAIL)) exit(retJson(ErrCode::ErrCode_10504));

        $mail = new PHPMailer(true);
		$mail->CharSet = PHPMailer::CHARSET_UTF8;

        // $send = $this->config->item('email');

        $send = $this->getEmailServer();

        $code = $this->codestr();
        // return true;
        //Server settings

        // $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        //Enable verbose debug output
        try {
            $mail->isSMTP();
            $mail->Host       = $send['sending_server'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $send['send_email'];
            $mail->Password   = $send['password'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->SMTPSecure = 'ssl';
            $mail->Port       = $send['sending_server_ssl'];

            //Recipients
            $mail->setFrom($send['send_email'], '花型检索');
            $mail->addAddress($param['email']);
            $mail->addReplyTo($send['send_email'], '花型检索');
            //Content
            $mail->isHTML(true);
            $mail->Subject = '验证码登录';
            $mail->Body    = "<head>
            <base target='_blank' />
            <style type='text/css'>::-webkit-scrollbar{ display: none; }</style>
            <style id='cloudAttachStyle' type='text/css'>#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>
            <style id='blockquoteStyle' type='text/css'>blockquote{display:none;}</style>
            <style type='text/css'>
                body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}
                td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}
                pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}
                th,td{font-family:arial,verdana,sans-serif;line-height:1.666}
                img{ border:0}
                header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}
                blockquote{margin-right:0px}
            </style>
        </head>
        <body tabindex='0' role='listitem'>
        <table width='700' border='0' align='center' cellspacing='0' style='width:700px;'>
            <tbody>
            <tr>
                <td>
                    <div style='width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;'>
                        <table border='0' cellpadding='0' cellspacing='0' width='700' height='39' style='font:12px Tahoma, Arial, 宋体;'>
                            <tbody><tr><td width='210'></td></tr></tbody>
                        </table>
                    </div>
                    <div style='width:680px;padding:0 10px;margin:0 auto;'>
                        <div style='line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;'>
                            <strong style='display:block;margin-bottom:15px;'>尊敬的用户：<span style='color:#f60;font-size: 16px;'></span>您好！</strong>
                            <strong style='display:block;margin-bottom:15px;'>
                                您正在进行<span style='color: red'>登录</span>操作，请在验证码输入框中输入：<span style='color:#f60;font-size: 24px'>$code</span>，以完成操作。120秒内有效
                            </strong>
                        </div>
                        <div style='margin-bottom:30px;'>
                            <small style='display:block;margin-bottom:20px;font-size:12px;'>
                                <p style='color:#747474;'>
                                    注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证帐户安全
                                    <br>（工作人员不会向你索取此验证码，请勿泄漏！)
                                </p>
                            </small>
                        </div>
                    </div>
                    <div style='width:700px;margin:0 auto;'>
                        <div style='padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;'>
                            <p>此为系统邮件，请勿回复<br>
                                请保管好您的邮箱，避免账号被他人盗用
                            </p>
                            <p>环思智慧科技</p>
                        </div>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
        </body>";
            $mail->AltBody = $code;
            $mail->send();
            $this->redis->Setex("pattern:email:" . $param['email'], 120, $code);
            return true;
        } catch (Exception $e) {
            echo '邮件发送失败: ', $mail->ErrorInfo;
        }
    }


    function codestr() {
        $arr = array_merge(range('a', 'b'), range('A', 'B'), range('0', '9'));
        shuffle($arr);
        $arr = array_flip($arr);
        $arr = array_rand($arr, 6);
        $res = '';
        foreach ($arr as $v) {
            $res .= $v;
        }
        return $res;
    }


    public function EditEmailServer($param) {
        if (!isset(
            $param['send_email'],
            $param['password'],
            $param['sending_server'],
            $param['receiving_server'],
            $param['receiving_server_no_ssl'],
            $param['receiving_server_ssl'],
            $param['sending_server_no_ssl'],
            $param['sending_server_ssl'],
        )) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $data = array(
            'send_email' =>  $param['send_email'],
            'password' =>  $param['password'],
            'sending_server' =>  $param['sending_server'],
            'receiving_server' =>  $param['receiving_server'],
            'receiving_server_no_ssl' =>  $param['receiving_server_no_ssl'],
            'receiving_server_ssl' =>  $param['receiving_server_ssl'],
            'sending_server_no_ssl' =>  $param['sending_server_no_ssl'],
            'sending_server_ssl' =>  $param['sending_server_ssl'],
        );


        if (isset($param['id']) && $param['id'] != '') {
            $this->Send_server_model->update($data, ['id' => $param['id']]);
        } else {
            $data['created'] = date("Y-m-d H:i:s");
            $this->Send_server_model->add($data);
        }


        return true;
    }




    public function getEmailServer() {
        $res = $this->Send_server_model->get_single([]);


        $ret = array(
	        'id' => empty($res) ?  '' : $res['id'],
            'send_email' => empty($res) ?  '' : $res['send_email'],
            'password' =>  empty($res) ?   '' : $res['password'],
            'sending_server' => empty($res) ?  '' : $res['sending_server'],
            'receiving_server' =>  empty($res) ?  '' :$res['receiving_server'] ,
            'receiving_server_no_ssl' => empty($res) ? '' : $res['receiving_server_no_ssl'] ,
            'receiving_server_ssl' =>  empty($res) ?   '' : $res['receiving_server_ssl'],
            'sending_server_no_ssl' =>  empty($res) ?   '' : $res['sending_server_no_ssl'],
            'sending_server_ssl' => empty($res) ?   '' : $res['sending_server_ssl'],
        );

        return $ret;
    }
}
